#include "collectpredefinationthread.h"

#include <QFile>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>
#include <QFileInfoListIterator>

CollectPredefinationThread::CollectPredefinationThread(const QString &dir,QObject *parent) :
    QThread(parent),
    m_requireStop(false)
{
    if (!QFile::exists(dir)) {
	m_dir = QCoreApplication::applicationDirPath() + "/devices";
    }else{
	m_dir = dir;
    }
}

CollectPredefinationThread::~CollectPredefinationThread(){
    stopCollect();
}

void CollectPredefinationThread::run() {
    QFileInfo info(m_dir);
    if (!info.isDir() ){
	emit collectError(ERR_DIR_NOT_FOUND,tr("找不到预定义文件的目录！请重新安装应用程序以解决该问题"));
	return;
    }

    QDir factory_dir(m_dir);

    clear();

    QFileInfoList factory_info_list = factory_dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs);

    foreach (QFileInfo factory_info,factory_info_list ) {
	QString factory_name = factory_info.baseName();
	QDir device_dir (factory_info.absoluteFilePath());

	QFileInfoList device_info_list = device_dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);

	QList<QSettings *> device_settings;
	QStringList device_names;

	device_settings = QList<QSettings *> ();
	device_names = QStringList ();

	foreach(QFileInfo device_info, device_info_list){
	    QSettings *setting = new QSettings(device_info.absoluteFilePath(),QSettings::IniFormat);
	    device_settings.append(setting);
	    device_names.append(device_info.baseName());
	}

	m_foundDeviceInfo.insert(factory_name,device_settings);
	m_foundDeviceList.insert(factory_name,device_names);

	m_foundFactoryList.append(factory_name);
    }

    emit collectFinish();
}

void CollectPredefinationThread::startCollect() {
    m_requireStop = false;
    start();
}

void CollectPredefinationThread::stopCollect() {
    m_requireStop = true;

    if (!wait(100) ){
	terminate();
	clear();
    }
}

void CollectPredefinationThread::clear () {
    m_foundDeviceInfo.clear();
    m_foundDeviceList.clear();
    m_foundFactoryList.clear();
}

QStringList CollectPredefinationThread::getFactoryList() const {
    return m_foundFactoryList;
}

void CollectPredefinationThread::getDeviceList(const QString &key,QStringList & devices, QList<QSettings *> &settings) const {
    QStringList null_r;
    QList<QSettings *> null_s;
    devices = m_foundDeviceList.value(key,null_r);
    settings = m_foundDeviceInfo.value(key,null_s);
}
